package com.elite.groovy.callback

import com.elite.groovy.kh.DHAESUtil
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.kh.getProperty
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 * @projectName: Groovy
 * @package: com.elite.groovy.callback
 * @className: ReportInfo
 * @description: 车险报案数据同步接口
 * @author: Rick
 * @date: 2024-11-12 16:13
 * @version: 1.0
 */

class ReportInfo implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(ReportInfo.class);

    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        long startTime = System.currentTimeMillis();

        //初始化
        String outData = "";



        // 获取所有Header
        Map<String, String> mapHeader = new HashMap<String, String>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            log.debug("Call Header-" + key + ":" + value);
            mapHeader.put(key, value);
        }


        String getMethod = request.getMethod();
        log.debug("HTTP请求调用类型 getMethod:" + getMethod);
        String PostBodyString = "";
        if(getMethod.equals("POST")) {
            try {
                //AES解密
                String PostBody = Util.getRequestBody(request, "utf-8");
                String assertKey = getProperty.get("DispatchAESPassword");
                PostBodyString = DHAESUtil.decrypt(PostBody, assertKey)
            }catch (Exception e){
                return '错误的加密串！';
            }
            log.info("[调用请求信息]:" + PostBodyString);
        }else{
            return '错误请求类型！';
        }



        //初始化数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        try {
            //落库方法
            try{
             outData = saveInfoData(jt, PostBodyString);
            }catch (Exception e){
                log.debug(e.toString());
                result.put("retCode", "-1");
                result.put("retMessage", "内部错误！");
                return result.toString();
            }
            log.debug("总耗时:" + (System.currentTimeMillis() - startTime).toString());
            return outData;

        } catch (Exception e) {
            outData = "HTTP请求调用错误，接口处理异常：" + e.getMessage();
            log.error(outData, e);
            return outData.toString();
        }
    }



/**
 *  车险报案数据落库
 */
    static String saveInfoData(JdbcTemplate jt, String PostBodyString) throws Exception {
        // 初始化返回
        JSONObject result = new JSONObject();
        JSONObject BodyOBJ = JSONObject.fromObject(PostBodyString)

        String Res_key = "Report_" + KHUtil.getRandomString(28);

        // 调用参数信息
        String ClmNo                      =  BodyOBJ.get("ClmNo")==null ? '':BodyOBJ.get("ClmNo");                          //报案号
        String PolicyNo                   =  BodyOBJ.get("PolicyNo");                       //保单号
        String PolicyBeginDate            =  BodyOBJ.get("PolicyBeginDate");                //保单起保日期yyyyMMdd
        String PolicyEndDate              =  BodyOBJ.get("PolicyEndDate");                  //保单止保日期yyyyMMdd
        String ConnectPolicyNo            =  BodyOBJ.get("ConnectPolicyNo");                //关联保单号
        String LinkerName                 =  BodyOBJ.get("LinkerName");                     //联系人姓名
        String LinkerPhone                =  BodyOBJ.get("LinkerPhone");                    //联系人电话
        String LinkerAddress              =  BodyOBJ.get("LinkerAddress");                  //联系地址
        String ReportTime                 =  BodyOBJ.get("ReportTime");                     //报案时间yyyyMMddHHmmss
        String LossAmount                 =  BodyOBJ.get("LossAmount");                     //报损金额
        String Peril                      =  BodyOBJ.get("Peril");                          //出险情况
        String ExamineAddress             =  BodyOBJ.get("ExamineAddress");                 //查勘地址
        String DamageTime                 =  BodyOBJ.get("DamageTime");                     //出险时间yyyyMMddHHmmss
        String LicenseNo                  =  BodyOBJ.get("LicenseNo");                      //车牌号码
        String DepartmentNo               =  BodyOBJ.get("DepartmentNo");                   //机构ID
        String AccidentCourse             =  BodyOBJ.get("AccidentCourse");                 //出险经过
        String ShareholderType            =  BodyOBJ.get("ShareholderType");                //股东业务标识
        String BusinessType               =  BodyOBJ.get("BusinessType");                   //业务分类 代码
        String OtherBusinessType          =  BodyOBJ.get("OtherBusinessType");              //其他业务标识 代码
        String EngineNo                   =  BodyOBJ.get("EngineNo");                       //发动机号
        String FrameNo                    =  BodyOBJ.get("FrameNo");                        //车架号
        String InsuredName                =  BodyOBJ.get("InsuredName");                    //被保险人
        String BrandName                  =  BodyOBJ.get("BrandName");                      //厂牌型号
        String DriverName                 =  BodyOBJ.get("DriverName");                     //驾驶人姓名
        String PerilCount                 =  BodyOBJ.get("PerilCount");                     //已出险次数
        String RobberyFlag                =  BodyOBJ.get("RobberyFlag");                    //盗抢定损
        String IsPersonDeathAccident      =  BodyOBJ.get("IsPersonDeathAccident");          //是否涉及人员死亡事故
        String IsGlass                    =  BodyOBJ.get("IsGlass");                        //是否玻璃案件
        String IsScene                    =  BodyOBJ.get("IsScene");                        //是否现场案件
        String AgentId                    =  BodyOBJ.get("AgentId");                        //接报案坐席ID，单点登录对应的客服坐席工号
        String DamageTypeCode             =  BodyOBJ.get("DamageTypeCode");                 //事故类型 代码
        String SubCertiType               =  BodyOBJ.get("SubCertiType");                   //责任认定书代码
        String FirstSiteFlag              =  BodyOBJ.get("FirstSiteFlag");                  //是否第一现场报案
        String DamageCode                 =  BodyOBJ.get("DamageCode");                     //出险原因代码
        String ReportBeginTime            =  BodyOBJ.get("ReportBeginTime");                //报案开始时间yyyyMMddHHmmss
        String ExaminePhone               =  BodyOBJ.get("ExaminePhone");                   //查勘员电话
        String SelfClaimFlag              =  BodyOBJ.get("SelfClaimFlag");                  //是否自助理赔案件1-是，0-否

        //规则校验写在这里
        String SelectSQL = ''' select clm_no from DH_REPORT where clm_no=? '''
        List SelectList = jt.queryForList(SelectSQL,ClmNo);

        if(SelectList.size()>0){
            result.put("retCode", "-2");
            result.put("retMessage", "clm_no已存在！");
            return result.toString();
        }

        if(ClmNo.equals("")||PolicyNo.equals("")){
            result.put("retCode", "-1");
            result.put("retMessage", "缺少关键参数！");
            return result.toString();
        }

        String InsertReportSQL = '''INSERT INTO DH_REPORT(REPORT_PKEY,
                                                         EXCLUSIVE_ID,
                                                         CLM_NO,
                                                         LINKER_NAME,
                                                         LINKER_PHONE,
                                                         LINKER_ADDRESS,
                                                         LICENSE_NO,
                                                         BRAND_NAME,
                                                         ENGINE_NO,
                                                         FRAME_NO,
                                                         INSURED_NAME,
                                                         REPORT_TIME,
                                                         HAPPENED_TIME,
                                                         REPORT_STATUS,
                                                         PERIL_COUNT,
                                                         POLICY_NO,
                                                         AGENT_ID,
                                                         REPORT_TYPE,
                                                         EXAMINE_ADDRESS,
                                                         DAMAGETYPECODE,
                                                         DAMAGECODE,
                                                         SUBCERTITYPE,
                                                         FIRSTSITEFLAG,
                                                         REPORTBEGINTIME,
                                                         EXAMINEPHONE,
                                                         SELF_CLAIM_FLAG,
                                                         ACCIDENT_COURSE) 
                                    VALUES (?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?,
                                            ?)''';

            int insertReportNum = jt.update(InsertReportSQL, Res_key, Res_key, ClmNo, LinkerName, LinkerPhone, LinkerAddress, LicenseNo, BrandName, EngineNo, FrameNo, InsuredName, ReportTime, DamageTime, 1, PerilCount, PolicyNo,1,AgentId,ExamineAddress,DamageTypeCode,DamageCode,SubCertiType,FirstSiteFlag,ReportBeginTime,ExaminePhone,SelfClaimFlag,AccidentCourse);
            log.debug("写入DH_REPORT结果:" + insertReportNum + " 【Res_key】:" + Res_key);



        if(SelfClaimFlag.equals("1")){
            String InsertOBTSQL = ''' INSERT INTO  OBT_SELF_LIST(SELF_ID,
                                                     REPORT_NO,
                                                     POLICY_NUM,
                                                     LICENSE_NO,
                                                     INSURED_NAME,
                                                     VISIT_STAT,
                                                     LINKER_NAME,
                                                     LINKER_PHONE,
                                                     REPORT_TIME,
                                                     DAMAGE_TIME,
                                                     ACCIDENT_COURSE,
                                                     BRAND_NAME,
                                                     DIAL_COUNT,
                                                     IS_SURVEY,
                                                     CREATE_TIME) 
                                    VALUES (?,
                                    ?,
                                    ?,
                                    ?,
                                    ?,
                                    0,
                                    ?,
                                    ?,
                                    ?,
                                    ?,
                                    ?,
                                    ?,
                                    0,
                                    0,
                                    sysdate) '''

            int insertOBTNum = jt.update(InsertOBTSQL, Res_key, ClmNo, PolicyNo, LicenseNo, InsuredName,LinkerName,LinkerPhone,ReportTime,DamageTime,AccidentCourse,BrandName);
            log.debug("写入OBT_SELF_LIST结果:" + insertOBTNum + " 【Res_key】:" + Res_key);
        }


            result.put("retCode", "1");
            result.put("retMessage", "success！");
            return result.toString();

    }


}